package com.demo.cryptology.digest;


import org.apache.commons.codec.binary.Hex;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class HMAC {

    private static final String HMAC_MD5 = "HmacMD5";

    public static String initMacKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(HMAC_MD5);
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }


    public static String hashMsgCode(byte[] data, String key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), HMAC_MD5);
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return new String(Hex.encodeHex(mac.doFinal(data)));
    }

    public static void main(String[] args) throws Exception {
        String macKey = initMacKey();
        System.out.println("key:\n" + macKey);
        String msg = "测试数据";
        String msgCode = hashMsgCode(msg.getBytes(), macKey);
        System.out.println("code:\n" + msgCode);
    }

}
